package com.my.algorithmlearning.leetcode;

import com.my.algorithmlearning.entity.TreeNode;
import org.springframework.util.Assert;

import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName Medium_98_ValidBST
 * @Description Medium_98_ValidBST
 * @Author wanghaiwei
 * @Date 2023/3/29 14:57
 */
public class Medium_98_ValidBST {
    boolean isValidBST = true;

    public boolean isValidBST(TreeNode root) {
        isValidBST = true;
        inorderTraversal(root);
        return isValidBST;
    }

    private List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null || !isValidBST) {
            return result;
        }
        List<Integer> leftResult = inorderTraversal(root.left);
        result.addAll(leftResult);
        if (leftResult.size() > 0 && leftResult.get(leftResult.size() - 1) >= root.val) {
            isValidBST = false;
        }
        result.add(root.val);
        List<Integer> rightResult = inorderTraversal(root.right);
        result.addAll(rightResult);
        if (rightResult.size() > 0 && rightResult.get(0) <= root.val) {
            isValidBST = false;
        }
        return result;
    }

    public static void main(String[] args) {
        Medium_98_ValidBST solution = new Medium_98_ValidBST();
        TreeNode t1 = new TreeNode(new Integer[]{2, 1, 3});
        Assert.isTrue(solution.isValidBST(t1), "Input: root = [2,1,3]，计算错误，预期true");

        t1 = new TreeNode(new Integer[]{5, 1, 4, null, null, 3, 6});
        Assert.isTrue(!solution.isValidBST(t1), "Input: root = [5,1,4,null,null,3,6]，计算错误，预期false");
    }
}
